
<template>
  <div class="min-h-screen bg-gray-50">
    <div class="pt-20">
      <div class="bg-white border-b border-gray-100">
        <div class="container mx-auto px-12 py-6 flex items-center justify-between">
          <div>
            <h1 class="text-3xl font-bold text-gray-900">我的课程</h1>
            <p class="text-gray-500 mt-1">管理课程系列与上传课程视频</p>
          </div>
          <div class="flex items-center gap-3">
            <el-input v-model="searchText" placeholder="搜索系列/视频" size="small" class="w-60" />
            <el-button type="primary" @click="openAddSeriesDialog">添加课程系列</el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="container mx-auto px-12 py-6">
      <div class="grid grid-cols-1 gap-4">
        <div v-for="series in filteredSeries" :key="series.id" class="bg-white rounded-lg shadow-sm border border-gray-100 overflow-hidden">
          <div class="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
            <div class="min-w-0">
              <div class="flex items-center gap-2 min-w-0">
                <div class="font-semibold text-gray-900 truncate">{{ series.name }}</div>
                <el-dropdown trigger="click">
                  <el-button size="small" circle plain>
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="startLiveForSeries(series)">开播</el-dropdown-item>
                      <el-dropdown-item @click="renameSeries(series)">重命名</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="text-xs text-gray-500 mt-1">共 {{ series.videos.length }} 节</div>
            </div>
            <div class="flex items-center gap-2">
              <el-button size="small" @click="uploadToSeries(series.id)">上传到该系列</el-button>
            </div>
          </div>
          <div class="p-3">
            <div v-if="series.videos.length" class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
              <div 
                v-for="video in series.videos" 
                :key="video.id" 
                class="rounded border border-gray-200 p-3 hover:border-blue-300 transition h-20 flex items-start justify-between"
              >
                <div class="min-w-0">
                  <div class="text-gray-900 font-medium truncate">{{ video.title }}</div>
                  <div class="text-xs text-gray-500 mt-1">{{ video.uploadedAt }}</div>
                </div>
                <div class="flex-shrink-0 ml-2">
                  <el-dropdown trigger="click">
                    <el-button size="small" circle>
                      <el-icon><MoreFilled /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                      <el-dropdown-item @click="renameVideo(video, series)">重命名</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </div>
            <div v-else class="text-sm text-gray-400 text-center py-8">暂无视频，点击上方按钮上传</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 上传课程视频对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传课程视频" width="560px">
      <div class="space-y-4">
        <el-form label-width="88px">
          <el-form-item label="课程系列">
            <el-select v-model="uploadSeries" placeholder="选择或输入系列名称" filterable allow-create default-first-option class="w-full">
              <el-option v-for="s in courseSeries" :key="s.id" :label="s.name" :value="s.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="视频标题">
            <el-input v-model="uploadVideoTitle" placeholder="如：Java开发1" />
          </el-form-item>
          <el-form-item label="上传文件">
            <el-upload
              class="w-full"
              drag
              :show-file-list="true"
              :auto-upload="true"
              :http-request="customUploadRequest"
              :before-upload="beforeUploadFile"
              :disabled="uploading"
              accept=".mp4,.mov,.avi,.mkv,.m4v">
              <div class="el-upload__text">
                拖拽视频到此处，或 <em>点击上传</em>
              </div>
            </el-upload>
          </el-form-item>
          <div class="text-xs text-gray-500 -mt-2">成功后会将视频加入所选系列（示例：当前为本地数据展示）</div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false" :disabled="uploading">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加课程系列对话框 -->
    <el-dialog v-model="addSeriesDialogVisible" title="添加课程系列" width="480px">
      <el-form label-width="88px">
        <el-form-item label="系列名称">
          <el-input v-model="newSeriesName" placeholder="例如：Java开发系列" maxlength="50" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addSeriesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createSeries">创建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { MoreFilled } from '@element-plus/icons-vue'
import { uploadFiles } from '@/api/teacher/homework'

const searchText = ref('')

// 课程系列（示例数据）
const courseSeries = ref([
  {
    id: 's-1',
    name: 'Java开发系列',
    videos: [
      { id: 'v-1', title: 'Java开发1：环境搭建', uploadedAt: '2025-10-10' },
      { id: 'v-2', title: 'Java开发2：基础语法', uploadedAt: '2025-10-11' }
    ]
  },
  {
    id: 's-2',
    name: '前端工程化系列',
    videos: [
      { id: 'v-3', title: '工程化1：包管理与脚手架', uploadedAt: '2025-10-09' }
    ]
  }
])

const filteredSeries = computed(() => {
  if (!searchText.value.trim()) return courseSeries.value
  const q = searchText.value.toLowerCase()
  return courseSeries.value
    .map(s => ({
      ...s,
      videos: s.videos.filter(v => v.title.toLowerCase().includes(q))
    }))
    .filter(s => s.name.toLowerCase().includes(q) || s.videos.length > 0)
})

// 上传
const uploadDialogVisible = ref(false)
const uploading = ref(false)
const uploadSeries = ref('')
const uploadVideoTitle = ref('')

// 添加课程系列
const addSeriesDialogVisible = ref(false)
const newSeriesName = ref('')
const openAddSeriesDialog = () => {
  newSeriesName.value = ''
  addSeriesDialogVisible.value = true
}
const createSeries = () => {
  const name = newSeriesName.value.trim()
  if (!name) {
    ElMessage.warning('请输入系列名称')
    return
  }
  // 重名校验（简单前端校验）
  const exists = courseSeries.value.some(s => s.name === name)
  if (exists) {
    ElMessage.warning('系列名称已存在')
    return
  }
  courseSeries.value.unshift({ id: `s-${Date.now()}`, name, videos: [] })
  addSeriesDialogVisible.value = false
  ElMessage.success('创建成功')
}

const uploadToSeries = (seriesId) => {
  uploadSeries.value = seriesId
  uploadDialogVisible.value = true
}

const beforeUploadFile = (file) => {
  if (!uploadSeries.value) {
    ElMessage.warning('请先选择课程系列（可直接输入新系列名称）')
    return false
  }
  if (!uploadVideoTitle.value) {
    uploadVideoTitle.value = file.name.replace(/\.[^.]+$/, '')
  }
  return true
}

const ensureSeriesExists = (seriesValue) => {
  // 如果选择的是现有系列id，直接返回
  const found = courseSeries.value.find(s => s.id === seriesValue)
  if (found) return found
  // 否则视为新系列名称，创建
  const newSeries = { id: `s-${Date.now()}`, name: String(seriesValue), videos: [] }
  courseSeries.value.unshift(newSeries)
  // 将选择值替换为新系列id
  uploadSeries.value = newSeries.id
  return newSeries
}

const customUploadRequest = async (options) => {
  const { file, onSuccess, onError } = options
  try {
    uploading.value = true
    const form = new FormData()
    form.append('file', file)
    await uploadFiles(form)
    const series = ensureSeriesExists(uploadSeries.value)
    series.videos.unshift({ id: `${Date.now()}`, title: uploadVideoTitle.value || file.name, uploadedAt: new Date().toISOString().slice(0,10) })
    uploadVideoTitle.value = ''
    ElMessage.success('上传成功')
    onSuccess && onSuccess({}, file)
  } catch (err) {
    ElMessage.error('上传失败，请稍后重试')
    onError && onError(err)
  } finally {
    uploading.value = false
  }
}

const previewVideo = (video) => {
  ElMessage.info(`预览：${video.title}`)
}

const startLiveFromVideo = (video, series) => {
  // 保留函数以便以后需要，但当前不开播
  ElMessage.info('当前开播入口在系列名称处的菜单中')
}

const renameVideo = (video, series) => {
  const newName = prompt('重命名视频', video.title)
  if (newName && newName.trim()) {
    video.title = newName.trim()
    ElMessage.success('已重命名')
  }
}

const deleteVideo = (video, series) => {
  const ok = confirm(`确定删除视频：${video.title}？`)
  if (!ok) return
  const s = courseSeries.value.find(s => s.id === series.id)
  if (!s) return
  s.videos = s.videos.filter(v => v.id !== video.id)
  ElMessage.success('已删除')
}

const startLiveForSeries = (series) => {
  const fakeClassId = `cls-${series.id || 'demo'}`
  sessionStorage.setItem('currentFakeClassId', fakeClassId)
  ElMessage.success(`已准备开播：${series.name}`)
}

const renameSeries = (series) => {
  const newName = prompt('重命名系列', series.name)
  if (newName && newName.trim()) {
    series.name = newName.trim()
    ElMessage.success('系列名称已更新')
  }
}
</script>

<style scoped>
.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
